import 'dart:async';
import 'dart:io';

import 'package:amap_flutter_location/amap_flutter_location.dart';
import 'package:amap_flutter_location/amap_location_option.dart';
import 'package:hygf/util/LoadingUtils.dart';
import 'package:permission_handler/permission_handler.dart';

import 'hap_location.dart';

class LocationGaode {
  LocationGaode._internal();

  factory LocationGaode() => _instance;
  static late final LocationGaode _instance = LocationGaode._internal();

  HapLocation _lastLocation = HapLocation(
    longitude: "0",
    latitude: "0",
    address: null,
  );
  late StreamSubscription<Map<String, Object>> _locationListener;
  final AMapFlutterLocation flutterLocation = AMapFlutterLocation();
  final AMapLocationOption aMapLocationOption = AMapLocationOption(
    needAddress: true,
    geoLanguage: GeoLanguage.DEFAULT,
    onceLocation: false,
    locationMode: AMapLocationMode.Hight_Accuracy,
    locationInterval: 2000,
    pausesLocationUpdatesAutomatically: false,
    desiredAccuracy: DesiredAccuracy.Best,
    desiredLocationAccuracyAuthorizationMode:
        AMapLocationAccuracyAuthorizationMode.FullAccuracy,
    distanceFilter: -1,
  );
  bool _isSubscriptionInitialized = false;
  late final StreamSubscription<Map<String, Object>> subscription;

  Future<void> initLocation() async {
    AMapFlutterLocation.updatePrivacyShow(true, true);
    AMapFlutterLocation.updatePrivacyAgree(true);
    AMapFlutterLocation.setApiKey(
      "e30aa637b90f9c6291efb2bc491db176",
      "22d3ea6586c7bbf2735ee6f12b69b999",
    );
    if (Platform.isIOS) {
      requestAccuracyAuthorization();
      await Permission.location.request();
    }
  }

  void requestAccuracyAuthorization() async {
    AMapAccuracyAuthorization currentAccuracyAuthorization = await flutterLocation.getSystemAccuracyAuthorization();
    if (currentAccuracyAuthorization == AMapAccuracyAuthorization.AMapAccuracyAuthorizationFullAccuracy) {
      print("精确定位类型");
    } else if (currentAccuracyAuthorization == AMapAccuracyAuthorization.AMapAccuracyAuthorizationReducedAccuracy) {
      print("模糊定位类型");
    } else {
      print("未知定位类型");
    }
  }

  ///开始定位
  Future<HapLocation> startLocation(
      Function(HapLocation location) callback) async {
    initLocation();
    AMapFlutterLocation.updatePrivacyShow(true, true);
    AMapFlutterLocation.updatePrivacyAgree(true);
    bool hasPermission = await requestLocationPermission();
    if (!hasPermission) {
      LoadingUtils.showToast("定位权限未开启");
      return _lastLocation;
    }
    if (!_isSubscriptionInitialized) {
      subscription = flutterLocation.onLocationChanged().listen((event) {
        print(event.toString());
        if (event['latitude'] != null) {
          _lastLocation = HapLocation(
            longitude: event['longitude'].toString(),
            latitude: event['latitude'].toString(),
            address: event['address'].toString(),
          );
          callback(_lastLocation);
          _stopLocation();
        }
      });
      _isSubscriptionInitialized = true;
    }
    flutterLocation.setLocationOption(aMapLocationOption);
    flutterLocation.startLocation();
    return _lastLocation;
  }

  void dispose() {
    subscription.cancel();
    flutterLocation.destroy();
  }

  ///停止定位
  void _stopLocation() {
    flutterLocation.stopLocation();
  }

  /// 申请定位权限
  /// 授予定位权限返回true， 否则返回false
  Future<bool> requestLocationPermission() async {
    //获取当前的权限
    var status = await Permission.location.status;
    if (status == PermissionStatus.granted) {
      //已经授权
      return true;
    } else {
      //未授权则发起一次申请
      status = await Permission.location.request();
      if (status == PermissionStatus.granted) {
        return true;
      } else {
        return false;
      }
    }
  }

  getLocation() async {
    bool hasPermission = await requestLocationPermission();
    if (!hasPermission) {
      LoadingUtils.showToast("未获取定位权限");
      return;
    }
  }
}
